/**
 * 商品发布页面
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2015-01-08 14:16:35
 * @for goodpublish.jsp
 */
var BSTMG = BSTMG || {};
BSTMG.goodpublish = {
	init: function(){
		var that = this;
		//分页功能
		that.showGoodsList("","","");		
		//查询
		that.query();	
		// 功能操作
		that.operatorGoods();
	},
	operatorGoods: function(){
		var $goodoperator = $("#goodoperator"),
			$goodsList = $("#goodsList"),
			$thead = $goodsList.find("thead"),
			$tbody = $goodsList.find("tbody");
		$goodoperator.on("click",".prodelete",function(){
			// 产品删除
			var ids = checkdBoxData();
			if ( ids.length == 0 ) { BSTYUN.dialog.warn("请选择一条数据！"); return false; }
			proDelete(ids);
		}).on("click",".proup",function(){
			// 产品上架
			var ids = checkdBoxData();
			if ( ids.length == 0 ) { BSTYUN.dialog.warn("请选择一条数据！"); return false; }
			proUp(ids)
		}).on("click",".prodown",function(){
			// 产品下架
			var ids = checkdBoxData();
			if ( ids.length == 0 ) { BSTYUN.dialog.warn("请选择一条数据！"); return false; }
			proDown(ids);
		}).on("click",".proapply",function(){
			// 申请发布
			var ids = checkdBoxData();
			if ( ids.length == 0 ) { BSTYUN.dialog.warn("请选择一条数据！"); return false; }
			proApply(ids);
		}).on("click",".procheck",function(){
			// 产品审核
			var ids = checkdBoxData();
			if ( ids.length == 0 ) { BSTYUN.dialog.warn("请选择一条数据！"); return false; }
			proCheck(ids);
		});
		/**
		 * [proDelete ajax产品删除]
		 * @param  {[Array]} ids   [需要删除的产品ID]
		 * @return {[undefined]}   [无返回值]
		 */
		function proDelete(ids){
			BSTYUN.dialog.confirm("确定要删除选中商品？",function(){
				$.ajax({
					type: 'post',
					url: "/sysAdmin/operate/goodsListAdmin/deleteGoods?ids="+ids,
					/*data:{
						ids : ids
					},*/
					dataType: 'json',
	//				data: ids.join(","),		//产品ID
					beforeSend: function(){},
					complete: function(){},
					success: function(data){
						if(data.isSuccess){
							location.href="/sysAdmin/goodsListAdmin/goodsList";
							//BSTMG.goodpublish.showGoodsList("","","");
						}else {
							BSTYUN.dialog.warn(data.message);
						}
					},
					error: function(){
					}
				})	
			});
		};
		/**
		 * [proUp ajax产品上架]
		 * @param  {[Array]} ids   [需要上架的产品ID]
		 * @return {[undefined]}   [无返回值]
		 */
		function proUp(ids){
			BSTYUN.dialog.confirm("确定要上架选中商品？",function(){
				$.ajax({
					type: 'post',
					url: "/sysAdmin/operate/goodsListAdmin/goodsOnline?ids="+ids,
					dataType: 'json',
	//				data: ids.join(","),		//产品ID
					beforeSend: function(){},
					complete: function(){},
					success: function(data){
						if(data.isSuccess){
							location.href="/sysAdmin/goodsListAdmin/goodsList";
							//BSTMG.goodpublish.showGoodsList("","","");
						}else {
							BSTYUN.dialog.warn(data.message);
						}
					},
					error: function(){
					}
				})
			});
		};
		/**
		 * [proDown ajax产品下架]
		 * @param  {[Array]} ids   [需要下架的产品ID]
		 * @return {[undefined]}   [无返回值]
		 */
		function proDown(ids){
			BSTYUN.dialog.confirm("确定要下架选中商品？",function(){
				$.ajax({
					type: 'post',
					url: "/sysAdmin/operate/goodsListAdmin/goodsOffline?ids="+ids,
					dataType: 'json',
//					data: ids.join(","),		//产品ID
					beforeSend: function(){},
					complete: function(){},
					success: function(data){
						if(data.isSuccess){
							location.href="/sysAdmin/goodsListAdmin/goodsList";
							//BSTMG.goodpublish.showGoodsList("","","");
						}else {
							BSTYUN.dialog.warn(data.message);
						}
					},
					error: function(){
					}
				})
			});
		};
		/**
		 * [proApply ajax产品申请发布]
		 * @param  {[Array]} ids   [需要申请发布的产品ID]
		 * @return {[undefined]}   [无返回值]
		 */
		function proApply(ids){
			BSTYUN.dialog.confirm("确定要申请发布选中商品？",function(){
				$.ajax({
					type: 'post',
					url: "/sysAdmin/operate/goodsListAdmin/goodsApplyPublish?ids="+ids,
					dataType: 'json',
					success: function(data){
						if(data.isSuccess){
							location.href="/sysAdmin/goodsListAdmin/goodsList";
							//BSTMG.goodpublish.showGoodsList("","","");
						}else {
							BSTYUN.dialog.warn(data.message);
						}
					},
					error: function(){
					}
				})
			});
		};
		/**
		 * [proCheck ajax产品审核]
		 * @param  {[Array]} ids   [需要审核的产品ID]
		 * @return {[undefined]}   [无返回值]
		 */
		function proCheck(ids){
			var dialog = null,
				html = '<form class="form-horizontal" role="form" style="width:300px"><div class="form-group agreegroup"><label class="col-sm-4 control-label">审核意见：</label><div class="col-sm-8"><label><input type="radio" name="agree" value="3" checked> 同意</label><label><input type="radio" name="agree" value="2"> 不同意</label></div></div><div class="form-group advisegroup"><label class="col-sm-4 control-label">意见说明：</label><div class="col-sm-8"><textarea class="form-control" rows="3"></textarea></div></div></form>';
			dialog = BSTYUN.dialog.creat({
				id : "checkpro",
				title: "审核",
				content : html
			});
			dialog.button(
				{
					name : "确定",
					callback : getConfirmResult,
					focus: true
				},{
					name : "取消"
				}
			);
			// 确定处理程序
			function getConfirmResult(){
				var $content = this.DOM.content,
					$agreegroup = $content.find(".agreegroup"),
					$advisegroup = $content.find(".advisegroup");
				// 获取选中的值 同意和意见
				var auditState = $.trim( $agreegroup.find("input:checked").val() ),
					reason = $.trim( $advisegroup.find("textarea").val() );
				$.ajax({
					type: 'post',
					url: "/sysAdmin/operate/goodsListAdmin/goodsAudit?ids="+ids,
					dataType: 'json',
					data:{
						auditState : auditState,
						reason : reason
					},
					//data: ids.join(","),		//产品ID
					beforeSend: function(){},
					complete: function(){},
					success: function(data){
						if(data.isSuccess){
							location.href="/sysAdmin/goodsListAdmin/goodsList";
							//BSTMG.goodpublish.showGoodsList("","","");
						}else {
							BSTYUN.dialog.warn(data.message);
						}
					},
					error: function(){
					}
				});
			}
		};

		// 选择产品
		function checkdBoxData(){
			var $checkbox = $tbody.find("input[type=checkbox]").filter(":checked"),
				ids = [];
			$checkbox.each(function(index,val){
				ids.push( $.trim( $(this).attr("data-id") ) );
			});
			return ids;
		};
		// 全选
		$thead.on("click",".checkall",function(){
			var $this = $(this),
			$current = $this.find(".simple"),
			$parent = $this.parents('table#goodsList'),
			$checkbox = $parent.find('input[type=checkbox]').not($current);
			$current.prop("checked") ? $checkbox.prop("checked",true) : $checkbox.prop("checked",false) ;
		});
		$tbody.on("click","input[type=checkbox]",function(){
			var $this = $(this),
				$all = $this.parents("tbody").eq(0).find("input[type=checkbox]"),
				$checkbox = $all.not($this).filter(":checked");
			var $checkall = $thead.find(".checkall input[type=checkbox]");
			( $this.prop("checked") && ($checkbox.length + 1) == $all.length ) ? $checkall.prop("checked",true) : $checkall.prop("checked",false) ;
		});
		
		// 表格操作
		$tbody.on("click",".categorydelete",function(){
			var $this = $(this);
				id = $.trim( $this.parents("tr.odd").find("input.simple").attr("data-id") );
				proDelete([id]);
		}).on("click",".categoryup",function(){
			var $this = $(this);
				id = $.trim( $this.parents("tr.odd").find("input.simple").attr("data-id") );
				proUp([id]);
		}).on("click",".categorydown",function(){
			var $this = $(this);
				id = $.trim( $this.parents("tr.odd").find("input.simple").attr("data-id") );
				proDown([id]);
		}).on("click",".categoryapply",function(){
			var $this = $(this);
			id = $.trim( $this.parents("tr.odd").find("input.simple").attr("data-id") );
			proApply([id]);
		}).on("click",".categorycheck",function(){
			var $this = $(this);
				id = $.trim( $this.parents("tr.odd").find("input.simple").attr("data-id") );
				proCheck([id]);
		});
		// 筛选排序
		$thead.on("click",".filter",function(){
			var $this = $(this),
				$dir = $this.next(),
				index = $this.parents("tr").children().index($this.parent()),
				store = [],
				sift = null,
				desc = $dir.hasClass("fa-sort-desc");
			
			$tbody.find('tr').each(function(sub,val){
				var $tr = $(this),
					txt = $tr.find("td").eq(index).text();
				var obj = {
						tr : $tr,
						txt : txt
				}
				store.push(obj);
			});
			if(desc){
				sift = function(a,b){
					var x1 = isNaN(a.txt) ? a.txt : Number( a.txt ) ,
						x2 = isNaN(b.txt) ? b.txt : Number( b.txt ) ;
					return x1 > x2 ? 1 : -1;
				}
				$dir.removeClass("fa-sort-desc").addClass("fa-sort-up");
			}else{
				sift = function(a,b){return a.txt > b.txt ? -1 : 1;} 
				$dir.removeClass("fa-sort-up").addClass("fa-sort-desc");
			}
			$.each( store.sort(sift) , function(){
				$tbody.append(this.tr);
			});
		});
	},
	showGoodsList: function(goodsName,isPublish,auditState){
		var url="/sysAdmin/goodsListAdmin/goodsList/search?goodsName="+goodsName+"&isPublish="+isPublish+"&auditState="+auditState;
		BSTMG.common.hjhPages(url,function(data){
			var goodsList = data.goodsList,
				adminUser = data.adminUser;
	        var $tbody = $("#goodsList tbody"),
	            html = '';
	        if (goodsList.length > 0) {
	            for (var i = 0; i < goodsList.length; i++) {
	            	var userInfo = goodsList[i];
	                var isPublish = setIsPublish(userInfo);
	                var auditState = setAuditState(userInfo);
	                html += '<tr class="odd">';
	                html += '<td><input type="checkbox" class="simple" data-id="'+userInfo.goodsId+'"></td>';
	                html += '<td>' + BSTMG.tools.checkNull(userInfo.goodsNum) + '</td>';
	                html += '<td>' + BSTMG.tools.checkNull(userInfo.goodsName) + '</td>';
	                html += '<td>' + BSTMG.tools.checkNull(userInfo.typeName) + '</td>';
	                html += '<td>' + BSTMG.tools.checkNull(userInfo.goodsDeveloper) + '</td>';
	                html += '<td>' + toDate(userInfo.publishTime,"yyyy-MM-dd hh:mm:ss") + '</td>';
	                html += '<td>' + BSTMG.tools.checkNull(auditState) + '</td>';
	                html += '<td>' + BSTMG.tools.checkNull(isPublish) + '</td>';
	                html += '<td>' + BSTMG.tools.checkNull(userInfo.adminName) + '</td>';
	                html += '<td class="opration">';
	                html += '<a href="/sysAdmin/goodsListAdmin/goodsDetail/'+userInfo.goodsId+'">查看</a> ';
	                if(userInfo.isPublish == 1){
	                	if(adminUser.roleId == 'MANAGER' || adminUser.roleId == 'OPERATOR') {
	                		html += '<a href="javascript:void(0);" class="categorydown">下架</a> ';
	                	}
	                }else if(userInfo.isPublish == 2){
	                	if(adminUser.roleId == 'MANAGER' || adminUser.roleId == 'PUBLISHER') {
	                		html += '<a href="/sysAdmin/goodsListAdmin/updateGoods/'+userInfo.goodsId+'">编辑</a> ';
	                		html += '<a href="javascript:void(0);" class="categorydelete">删除</a> ';
	                	}
                		if(adminUser.roleId == 'MANAGER' || adminUser.roleId == 'OPERATOR') {
                			html += '<a href="javascript:void(0);" class="categoryup">上架</a> ';
	                	}
	                }else if(userInfo.isPublish == null || userInfo.isPublish == "" || userInfo.isPublish == 0){
	                	if(adminUser.roleId == 'MANAGER' || adminUser.roleId == 'PUBLISHER') {
	                		html += '<a href="/sysAdmin/goodsListAdmin/updateGoods/'+userInfo.goodsId+'">编辑</a> ';
	                		html += '<a href="javascript:void(0);" class="categorydelete">删除</a> ';
	                	}
	                	if(userInfo.auditState == 1){
	                		if(adminUser.roleId == 'MANAGER' || adminUser.roleId == 'OPERATOR') {
	                			html += '<a href="javascript:void(0);" class="categorycheck">审核</a> ';
		                	}
	                	}else if(userInfo.auditState == 0){
	                		if(adminUser.roleId == 'MANAGER' || adminUser.roleId == 'PUBLISHER') {
	                			html += '<a href="javascript:void(0);" class="categoryapply">申请</a> ';
	                		}
	                	}
	                }
	                html += '</td></tr>';
	            }
	            $tbody.html(html);
	        } else {
	            var $tr = '<tr class="odd"><td colspan="10">暂无数据！</td></tr>';
	            $tbody.html($tr);
	        }
		});
	},
	query : function(){
		$('#query').on('click',function(){
			var goodsName = $('#goodsName').val();
			var isPublish = $('#isPublish').val();
			var auditState = $('#auditState').val();
			BSTMG.goodpublish.showGoodsList(goodsName,isPublish,auditState);
		})
	},
};

$(function(){
	BSTMG.goodpublish.init();
});

//回车键查询功能
function keyQuery(){
	if(event.keyCode == 13){
		$('#query').trigger("click");
	}
}
//设置发布状态
function setIsPublish(userInfo){
	if(userInfo.isPublish == 0||userInfo.isPublish == null||userInfo.isPublish == ""){
		return "——";
	}else if(userInfo.isPublish == 1){
		return "已上架";
	}else if(userInfo.isPublish == 2){
		return "已下架";
	}else{
		return "";
	}
}
//设置审核状态
function setAuditState(userInfo){
	if(userInfo.auditState == 0){
		return "未提交";
	}else if(userInfo.auditState == 1){
		return "未审核";
	}else if(userInfo.auditState == 2){
		return "审核不通过";
	}else if(userInfo.auditState == 3){
		return "审核通过";
	}else{
		return "";
	}
}
